package controlador;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;

import Modelo.Asistente;
import Modelo.Mensaje_publicitario;
import Modelo.Patrocinador;

public class HiloMensajePatrocinio implements Runnable {
private Patrocinador patrocinador;
private ArrayList<Asistente> asistentes;

String shortcode="2020";
String pass="first";
String server="http://192.168.101.4:8080/broker";

public String enviarMensaje(String celular, String mensaje) {
	String result = "";

	try {
		// Construct data
		String data = URLEncoder.encode("shortcode", "UTF-8") + "="
				+ URLEncoder.encode(shortcode, "UTF-8");
		data += "&" + URLEncoder.encode("password", "UTF-8") + "="
				+ URLEncoder.encode(pass, "UTF-8");
		data += "&" + URLEncoder.encode("destinos", "UTF-8") + "="
				+ URLEncoder.encode(celular, "UTF-8");
		data += "&" + URLEncoder.encode("contenido", "UTF-8") + "="
				+ URLEncoder.encode(mensaje, "UTF-8");

		// Send data
		URL url = new URL(server + "/brokerSend");
		URLConnection conn = url.openConnection();
		conn.setDoOutput(true);
		OutputStreamWriter wr = new OutputStreamWriter(
				conn.getOutputStream());
		wr.write(data);
		wr.flush();

		// Get the response
		BufferedReader rd = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		String line;
		while ((line = rd.readLine()) != null) {
			result = result + line + "\n";
		}
		wr.close();
		rd.close();
	} catch (Exception e) {
		result = "error";
	}

	return result;

}
public void run() {

boolean seguir=true;
	
	for(int cont=0;cont<patrocinador.getCantidad_mensajes();cont++){

	
	for(Asistente a: asistentes){
		enviarMensaje(a.getCelular(), patrocinador.getCod_mensaje().getMensaje());
	System.out.println(a.getCelular()+a.getNombre());
	
	
	}
	try {
		Thread.sleep(5000);
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		
	}
		

		
	
			
		seguir=false;
		try {
			this.finalize();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		}
		
		
		
	

	public HiloMensajePatrocinio(Patrocinador patrocinador,
		ArrayList<Asistente> asistentes) {
	super();
	this.patrocinador = patrocinador;
	this.asistentes = asistentes;
}


	

}
